<template>
    <div class="article-detail">
        <div class="defaultBg">
            <div class="act-form-contant" v-bind:style="{ height: formHeight }">
                <is-view
                    v-if="actDataIsReady && isView == 1 && actImgIsReady"
                    :actDetailData="actDetailData"
                    :actImgList="actImgList">
                </is-view>
                <not-view
                    v-if="actDataIsReady && isView == 0 && actImgIsReady"
                    :actDetailData="actDetailData"
                    :actImgList="actImgList">
                </not-view>
            </div>
        </div>

        <el-dialog title="活动审批" :visible.sync="approvalDialogVisible" width="40%" :beforeClose="approvalCancel">
            <el-form :model="approvalForm" ref="approvalForm">
                <el-form-item label="审批意见" prop="approvalDesc" :label-width="'80px'">
                    <el-input
                        type="textarea"
                        :rows="3"
                        v-model="approvalForm.approvalDesc"
                        placeholder="请输入审批意见">
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="approvalAgree(1)">通过申请</el-button>
                <el-button size="small" type="warning" @click="approvalReject(2)">驳回申请</el-button>
                <el-button size="small" @click="approvalCancel">取 消</el-button>
            </div>
        </el-dialog>

        <div class="bottom-button" ref="Button">
            <el-button
                icon="el-icon-back"
                type="warning"
                size="small"
                @click="$router.push(`/article/articleList`)">
                返回
            </el-button>
            <el-button
                icon="el-icon-document-checked"
                type="primary" size="small"
                v-if="isView == 0"
                @click="approvalDialogVisible=true">
                审批
            </el-button>
            <el-button
                icon="el-icon-tickets"
                type="primary" size="small"
                v-if="isView == 1 && (actDetailData.approvalStatus == 1 && actDetailData.actType == 1) && (account == actDetailData.organizerAccount || roleCode==='super_admin' || role_code==='admin')"
                @click="showEntryList">
                查看参赛文件
            </el-button>
            <el-button
                icon="el-icon-document-checked"
                type="primary" size="small"
                v-if="isView == 1 && actDetailData.approvalStatus === 1 && (actDetailData.teacherAccount === account || actDetailData.organizerAccount === account)"
                @click="showScoreList">
                加分名单
            </el-button>
            <el-button
                icon="el-icon-document-checked"
                type="danger" size="small"
                v-if="isView == 1 && actDetailData.approvalStatus === 2 && (actDetailData.organizerAccount === account)"
                @click="editACT">
                活动修改
            </el-button>
        </div>

        <el-dialog title="加分名单" :visible.sync="showScoreListFlag" style="paddingBottom:20px;">
            <Mtable v-if="showScoreListFlag" :tableColumns="scoreCoulums" :isInline="true" :tableList="scoreList"
                :count="1000" :isPagination="false" :isButton="false" :tableHeight="'350px'">
            </Mtable>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showScoreListFlag = false">取 消</el-button>
                <el-button v-if="actDetailData.teacherAccount === account && actDetailData.scoreApprovalStatus != 1" type="primary" @click="approvalScoreFn">通过审批</el-button>
                <el-button v-if="actDetailData.organizerAccount === account && actDetailData.scoreApprovalStatus != 1" type="primary" @click="addScoreFn">添加加分用户</el-button>
            </div>
        </el-dialog>

        <el-dialog title="学生参赛文件" :visible.sync="showEntryListFlag">
            <Mtable v-if="showEntryListFlag" :tableColumns="entryCoulums" :isInline="true" :tableList="entryList"
                :count="1000" :isPagination="false" :isButton="false" :tableHeight="'350px'">
            </Mtable>
        </el-dialog>

        <el-dialog title="评分" :visible.sync="showEntryScoreFormFlag">
            <el-form label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="活动加分：">
                            <el-checkbox-group v-model="scoreTypeList" @change="scoreTypeListChange" class="checkbox-g">
                                <el-checkbox label="0" class="checkbox-i">
                                    创新分：
                                    <el-input v-model="chuangxinScore" :disabled="cInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                                <el-checkbox label="1" class="checkbox-i">
                                    学业分：
                                    <el-input v-model="xueyeScore" :disabled="xInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                                <el-checkbox label="2" class="checkbox-i">
                                    思想分：
                                    <el-input v-model="sixiangScore" :disabled="sInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                                <el-checkbox label="3" class="checkbox-i">
                                    文体分：
                                    <el-input v-model="wentiScore" :disabled="wInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showEntryScoreFormFlag = false">取 消</el-button>
                <el-button type="primary" @click="marchScoreFn">评 分</el-button>
            </div>
        </el-dialog>

        <!-- TODO: -->
        <el-dialog title="添加一个数据" :visible.sync="showAddScoreDialog">
            <el-form label-width="100px">
                <el-row>
                    <el-col :span="14">
                        <el-form-item label="学生账号：">
                            <el-input v-model="addScoreUserAccount" placeholder="请输入学生学号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="活动加分：">
                            <el-checkbox-group v-model="addScoreTypeList" @change="scoreTypeListChange" class="checkbox-g">
                                <el-checkbox label="0" class="checkbox-i">
                                    创新分：
                                    <el-input v-model="chuangxinScore" :disabled="cInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                                <el-checkbox label="1" class="checkbox-i">
                                    学业分：
                                    <el-input v-model="xueyeScore" :disabled="xInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                                <el-checkbox label="2" class="checkbox-i">
                                    思想分：
                                    <el-input v-model="sixiangScore" :disabled="sInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                                <el-checkbox label="3" class="checkbox-i">
                                    文体分：
                                    <el-input v-model="wentiScore" :disabled="wInput" placeholder="请输入内容"></el-input>
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showAddScoreDialog = false">取 消</el-button>
                <el-button type="primary" @click="addOneUserScoreFn">添 加</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getACTDetailInfo, approvalACT, getACTImg, getActScoreFile, approvalScoreList, getEntryList, marchScore } from '@/api/article'
import { userIsExist } from '@/api/user'
import Mtable from '@/components/MTable/MTable.vue'
import IsViewForm from './components/IsViewForm.vue'
import NotViewForm from './components/NotViewForm.vue'
export default {
    name: 'article-detail',
    components: {
        [IsViewForm.name]: IsViewForm,
        [NotViewForm.name]: NotViewForm,
        Mtable
    },
    data () {
        return {
            formHeight: '', // 表单自适应高度
            actId: this.$route.params.actId, // 活动id
            isView: this.$route.params.isView, // 是否为查看模式
            actDataIsReady: false, // 数据是否请求完成 
            actDetailData: {}, // 活动详细信息
            actImgList: [], // 活动图片列表
            actImgIsReady: false, // 活动图片是否请求完成

            // 审批弹窗配置
            approvalDialogVisible: false,
            approvalForm: {
                actId: this.$route.params.actId,
                approvalDesc: '',
                approvalStatus: ''
            },

            // 加分名单 
            showScoreListFlag: false,
            scoreCoulums: [
                { name: 'userName', label: '学生名称' },
                { name: 'scoreTypeStatus', label: '加分类型' },
                { name: 'score', label: '分数' },
                { name: 'scoreApprovalStatusDesc', label: '审批状态' },
                // TODO:
            ],
            scoreList: [],

            // 学生参赛文件列表
            showEntryListFlag: false,
            entryCoulums: [
                { name: 'userAccount', label: '学生账号' },
                { name: 'userName', label: '学生名称' },
                { name: 'entryApprovalStatusDetail', label: '是否评分' },
                {
                    name: 'operation', label: '操作', align: "center", width: "260",
                    /**
                     * @param {Object} h 渲染函数参数对象
                     * @param {Number} index 该行下角标
                     * @param {Object} row 所在行对象
                     * @param {Object} column 所在列对象
                     * @param {Object} scope 表格项对象
                    */
                    render: (h, index, row, column, scope) => {
                        return (
                            <span>
                                <el-button icon="el-icon-document" size="small" type="primary" nativeOn-click={(e) => {
                                    let url = process.env.VUE_APP_BASE_API + row.entryPath
                                    window.open(url, "_blank", "width=900, height=700")
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>查看文件</el-button>
                                <el-button icon="el-icon-check" size="small" type="success" v-show={row.entryApprovalStatus == 0} nativeOn-click={(e) => {
                                    this.showEntryScoreFormFlag = true
                                    this.scoreActId = row.actId
                                    this.scoreUserAccount = row.userAccount
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>评分</el-button>
                            </span >
                        )
                    },
                }
            ],
            entryList: [],

            // 参赛文件加分选项
            showEntryScoreFormFlag: false,
            scoreTypeList: [],
            scoreActId: '',
            scoreUserAccount: '',

            chuangxinScore: 0.5,
            xueyeScore: 0.5,
            sixiangScore: 0.5,
            wentiScore: 0.5,
            cInput: true,
            xInput: true,
            sInput: true,
            wInput: true,

            // 加分名单添加一个数据 TODO:
            showAddScoreDialog: false,
            addScoreTypeList: [],
            addScoreUserAccount: '',
        }
    },
    computed: {
        ...mapGetters(['roleCode', 'name', 'account']),
    },
    methods: {
        async getActData () {
            const { data } = await getACTDetailInfo({ actId: this.actId })
            this.actDetailData = data
            this.actDataIsReady = true
        },

        async getActImgList () {
            const { data } = await getACTImg({ actId: this.actId })
            data.forEach(item => {
                item.imgPath = process.env.VUE_APP_BASE_API + item.imgPath
            })
            this.actImgList = data
            this.actImgIsReady = true
        },

        // 审批活动
        async approvalFn () {
            const res = await approvalACT(this.approvalForm)
            if (res.hasOk) {
                this.$message({
                    message: '审批成功！',
                    type: 'success'
                })
                // 跳转到查看页面
                this.$router.push(`/article/aticleDetail/${this.actId}/1`)
            } else {
                this.$message({
                    message: res.message,
                    type: 'error'
                })
            }
        },

        // 活动审批取消
        approvalCancel () {
            this.approvalDialogVisible = false
            this.$refs.approvalForm.resetFields()
        },

        // 通过活动申请
        approvalAgree (approvalStatus) {
            this.approvalForm.approvalStatus = approvalStatus
            if (!this.approvalForm.approvalDesc) {
                this.approvalForm.approvalDesc = '申请通过'
            }
            this.approvalFn()
        },

        // 驳回活动申请
        approvalReject (approvalStatus) {
            this.approvalForm.approvalStatus = approvalStatus
            if (!this.approvalForm.approvalDesc) {
                this.approvalForm.approvalDesc = '驳回申请'
            }
            this.approvalFn()
        },

        // 加分名单
        async showScoreList () {
            // 请求活动的加分名单
            const res = await getActScoreFile(this.actId)
            let result = []
            res.data.forEach((item) => {
                const index = result.findIndex((ele) => ele.userName === item.userName)
                if (index === -1) {
                    result.push(item)
                } else {
                    result[index].score += '、' + item.score
                    result[index].scoreTypeStatus += '、' + item.scoreTypeStatus
                }
            })
            this.scoreList = result
            this.showScoreListFlag = true
        },
        // 加分名单通过审批
        async approvalScoreFn () {
            const res = await approvalScoreList(this.actId)
            if (res.hasOk) {
                this.$message.success('审批成功')
                this.getActData()
                this.showScoreListFlag = false
            } else {
                this.$message.error(res.message)
            }
        },

        // 参赛文件列表
        async showEntryList () {
            const res = await getEntryList(this.actId)
            if (res.hasOk) {
                this.entryList = res.data
                this.showEntryListFlag = true
            } else {
                this.$message.warning('未有人提交参赛文件')
            }

        },

        scoreTypeListChange (value) {
            this.cInput = !value.some((item) => item === '0')
            this.xInput = !value.some((item) => item === '1')
            this.sInput = !value.some((item) => item === '2')
            this.wInput = !value.some((item) => item === '3')
        },

        async marchScoreFn () {
            let marchScoreTypeList = []
            if (!this.cInput) {
                marchScoreTypeList.push({ scoreType: 0, score: this.chuangxinScore })
            }
            if (!this.xInput) {
                marchScoreTypeList.push({ scoreType: 1, score: this.xueyeScore })
            }
            if (!this.sInput) {
                marchScoreTypeList.push({ scoreType: 2, score: this.sixiangScore })
            }
            if (!this.wInput) {
                marchScoreTypeList.push({ scoreType: 3, score: this.wentiScore })
            }

            if (marchScoreTypeList.length === 0) {
                this.$message({
                    message: '请至少选择一个加分项',
                    type: 'error'
                })
                return
            }
            JSON.stringify(marchScoreTypeList)
            const res = await marchScore({
                marchScoreTypeList: JSON.stringify(marchScoreTypeList),
                actId: this.scoreActId,
                userAccount: this.scoreUserAccount
            })
            await this.showEntryList()
            this.showEntryScoreFormFlag = false
        },

        // TODO:
        addScoreFn () {
            this.showAddScoreDialog = true
        },
        async addOneUserScoreFn () {
            const userRes = await userIsExist(this.addScoreUserAccount)
            if (userRes.hasOk) {
                let marchScoreTypeList = []
                if (!this.cInput) {
                    marchScoreTypeList.push({ scoreType: 0, score: this.chuangxinScore })
                }
                if (!this.xInput) {
                    marchScoreTypeList.push({ scoreType: 1, score: this.xueyeScore })
                }
                if (!this.sInput) {
                    marchScoreTypeList.push({ scoreType: 2, score: this.sixiangScore })
                }
                if (!this.wInput) {
                    marchScoreTypeList.push({ scoreType: 3, score: this.wentiScore })
                }

                if (marchScoreTypeList.length === 0) {
                    this.$message({
                        message: '请至少选择一个加分项',
                        type: 'error'
                    })
                    return
                }
                JSON.stringify(marchScoreTypeList)

                // 记录加分分数和用户
                const res = await marchScore({
                    marchScoreTypeList: JSON.stringify(marchScoreTypeList),
                    actId: this.actId,
                    userAccount: 'suneo'
                })
                if (res.hasOk) {
                    this.$message.success('添加成功')
                    this.showScoreList()
                    this.chuangxinScore = 0.5
                    this.xueyeScore = 0.5
                    this.sixiangScore = 0.5
                    this.wentiScore = 0.5
                    this.cInput = true
                    this.xInput = true
                    this.sInput = true
                    this.wInput = true
                    this.addScoreTypeList = []
                    this.addScoreUserAccount = ''
                    this.showAddScoreDialog = false
                }
            } else {
                this.$message.warning('用户不存在，请检查输入账号是否正确')
            }
        },

        // 设置表单的自适应高度
        setFormHeight () {
            let fullHeight = document.body.clientHeight - this.$refs.Button.offsetHeight - 90
            this.formHeight = fullHeight > 300 ? fullHeight + 'px' : '300px'
            this.isHeightReady = true
        },

        editACT () {
            this.$router.push(`/article/articleEdit/${this.actId}`)
        }

    },
    created () {
        this.getActData()
        this.getActImgList()
    },
    mounted () {
        this.setFormHeight()
        let that = this
        window.onresize = function temp () {
            that.setFormHeight()
        }
    },
}
</script>

<style lang="scss" scoped>
.article-detail {
    position: relative;
    height: inherit;
}
.act-form-contant {
    width: 100%;
    height: 100%;
    padding: 20px 10px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    overflow: auto;
}

.checkbox-g {
    .checkbox-i {
        margin-right: 100px;
    }
}

::v-deep .el-dialog__body {
    padding-bottom: 20px;
}

.bottom-button {
    position: absolute;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 50px;
    border-top: 1px solid #d9d9d9;
    background-color: #fff;
}
</style>